import {ElMessage} from "element-plus";
import CacheStore from "./cacheStore";

const encrypt = require('./crypto')
const axios = require('axios')
const http = require('http')
const https = require('https')
const {URLSearchParams} = require('url')
const querystring = require('querystring')

axios.defaults.baseURL = 'http://localhost:4001';
axios.interceptors.response.use(res => {
    return res.data;
})
/**
 * 构造客户端代理信息
 * @param ua
 * @return {string|boolean}
 */
const chooseUserAgent = (ua = false) => {
    const userAgentList = {
        mobile: [
            // iOS 13.5.1 14.0 beta with safari
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.',
            // iOS with qq micromsg
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML like Gecko) Mobile/14A456 QQ/6.5.7.408 V1_IPH_SQ_6.5.7_1_APP_A Pixel/750 Core/UIWebView NetType/4G Mem/103',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f27) NetType/WIFI Language/zh',
            // Android -> Huawei Xiaomi
            'Mozilla/5.0 (Linux; Android 9; PCT-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.311 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; U; Android 9; zh-cn; Redmi Note 8 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/12.5.22',
            // Android + qq micromsg
            'Mozilla/5.0 (Linux; Android 10; YAL-AL00 Build/HUAWEIYAL-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.62 XWEB/2581 MMWEBSDK/200801 Mobile Safari/537.36 MMWEBID/3027 MicroMessenger/7.0.18.1740(0x27001235) Process/toolsmp WeChat/arm64 NetType/WIFI Language/zh_CN ABI/arm64',
            'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BKK-AL10 Build/HONORBKK-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.6 Mobile Safari/537.36',
        ],
        pc: [
            // macOS 10.15.6  Firefox / Chrome / Safari
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15',
            // Windows 10 Firefox / Chrome / Edge
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586',
            // Linux 就算了
        ],
    }
    let realUserAgentList =
        userAgentList[ua] || userAgentList.mobile.concat(userAgentList.pc)
    return ['mobile', 'pc', false].indexOf(ua) > -1
        ? realUserAgentList[Math.floor(Math.random() * realUserAgentList.length)]
        : ua
}
/**
 * 自定义axios请求封装
 * @param method 请求方式
 * @param url url
 * @param param 请求参数
 * @param body 请求体
 * @param options 扩展参数
 * @return {Promise<unknown>}
 */
export const createRequest = (method, url, param, body, options) => {
    return new Promise((resolve, reject) => {
        let headers = {}
        // headers['User-Agent'] = chooseUserAgent(options.ua)
        // if (method.toUpperCase() === 'POST') {
        //     headers['Content-Type'] = 'application/json;charset=UTF-8'
        // }
        if (options.realIP) {
            headers['X-Real-IP'] = options.realIP
        }
        let access_token = CacheStore.getCookie('access_token')
        if (access_token !== '') {
            headers['Authorization'] = access_token
        }

        const answer = {status: 500, body: {}, cookie: [], message: ''}
        let settings = {
            method: method,
            url: url,
            headers: headers,
            // params参数使用param
            params: param,
            // data参数为post请求的body
            data: body,
            httpAgent: new http.Agent({keepAlive: true}),
            httpsAgent: new https.Agent({keepAlive: true}),
        }
        // console.log('这里发送axios')
        axios(settings).then((res) => {
            // console.log(res)
            answer.status = res.code
            answer.body = res.data || {}
            answer.message = res.message || ''

            // 异常状态统一归为400
            answer.status = 100 < answer.status && answer.status < 600 ? answer.status : 400
            if (answer.status === 200) {
                resolve(answer)
            } else {
                reject(answer)
            }
        }).catch((err) => {
            if (err.status === 401) {
                ElMessage.warning("未登录")
            }
            console.log("request error:", err)
            if (err.response === undefined) {
                reject(answer)
            } else {
                let response = err.response.data
                answer.status = response.status
                answer.body = response.data || {}
                answer.message = response.message || ''
                reject(answer)
            }
        })
    })
}
// module.exports = createRequest
